#!/bin/bash

echo "=== SSO API 测试脚本 ==="

# 基础URL
BASE_URL="http://localhost:8080"
AUTH_URL="http://localhost:8081"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 测试函数
test_api() {
    local method=$1
    local url=$2
    local data=$3
    local description=$4
    
    echo -e "${YELLOW}测试: $description${NC}"
    echo "请求: $method $url"
    
    if [ -n "$data" ]; then
        echo "数据: $data"
        response=$(curl -s -X $method "$url" \
            -H "Content-Type: application/json" \
            -d "$data")
    else
        response=$(curl -s -X $method "$url")
    fi
    
    echo "响应: $response"
    echo "---"
}

# 等待服务启动
echo "等待服务启动..."
sleep 10

# 测试登录
echo -e "${GREEN}=== 测试登录 ===${NC}"
login_response=$(curl -s -X POST "$AUTH_URL/auth/login" \
    -H "Content-Type: application/json" \
    -d '{
        "username": "admin",
        "password": "123456"
    }')

echo "登录响应: $login_response"

# 提取token
token=$(echo $login_response | grep -o '"accessToken":"[^"]*"' | cut -d'"' -f4)

if [ -n "$token" ]; then
    echo -e "${GREEN}获取到token: ${token:0:20}...${NC}"
    
    # 测试获取用户信息
    echo -e "${GREEN}=== 测试获取用户信息 ===${NC}"
    curl -s -X GET "$AUTH_URL/auth/userinfo" \
        -H "Authorization: Bearer $token"
    
    echo ""
    
    # 测试验证token
    echo -e "${GREEN}=== 测试验证token ===${NC}"
    curl -s -X POST "$AUTH_URL/auth/validate" \
        -H "Authorization: Bearer $token"
    
    echo ""
    
    # 测试登出
    echo -e "${GREEN}=== 测试登出 ===${NC}"
    curl -s -X POST "$AUTH_URL/auth/logout" \
        -H "Authorization: Bearer $token"
    
    echo ""
    
else
    echo -e "${RED}登录失败，未获取到token${NC}"
fi

echo -e "${GREEN}=== 测试完成 ===${NC}" 